# jobs\views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.http import HttpResponse, Http404, HttpResponseRedirect
from django.shortcuts import render

# Create your views here.
from django.template import loader
from django.views.generic import CreateView, DetailView

from jobs.models import Job, Cities, JobTypes, Resume


def job_list(request):
    jobs = Job.objects.order_by('job_type')
    # template = loader.get_template('job_list.html')
    context = {'job_list_html': jobs}

    for job in jobs:
        job.city_name_html = Cities[job.job_city][1]
        job.job_type_html = JobTypes[job.job_type][1]
    # return HttpResponse(template.render(context))
    return render(request, 'job_list.html', context)


def job_detail(request, job_id):
    try:
        job = Job.objects.get(pk=job_id)
        job.city_name = Cities[job.job_city][1]
    except Job.DoesNotExist as e:
        raise Http404(f"{e}")

    return render(request, 'job_detail.html', {'job': job})


class ResumeCreateView(LoginRequiredMixin, CreateView):
    # 简历职位页面
    template_name = 'resume_form.html'
    success_url = '/job_list/'
    model = Resume
    fields = ["username", "city", "phone",
              "email", "apply_position", "gender",
              "bachelor_school", "master_school", "major", "degree",
              "candidate_introduction", "work_experience", "project_experience"]

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self.object = None

    # 从URL请求参数带入默认值
    def get_initial(self):
        initial_dict = {}
        response = self.request.GET
        for key in response:
            initial_dict[key] = self.request.GET.get(key)
        return initial_dict

    # 简历跟当前用户关联
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.applicant = self.request.user
        self.object.save()
        return HttpResponseRedirect(self.get_success_url())


class ResumeDetailView(DetailView):
    """简历详情页"""
    model = Resume
    template_name = 'resume_detail.html'
